package com.sap.com.seckill.controller;

import com.sap.com.seckill.service.SeckillService;
import com.sap.com.seckill.to.SeckillSkuRedisTO;
import com.sap.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Controller
public class SeckillController {

    @Autowired
    SeckillService seckillService;

    /**
     * 返回当前时间可以参与得秒杀商品信息
     *
     * @return
     */
    @GetMapping("getCurrentSeckillSkus")
    @ResponseBody
    public R getCurrentSeckillSkus() {
        log.info("getCurrentSeckillSkus=====>>>");
        List<SeckillSkuRedisTO> seckillSkus = seckillService.getCurrentSeckillSkus();
        return R.ok().setData(seckillSkus);
    }

    @GetMapping("/sku/seckill/{skuId}")
    @ResponseBody
    public R getSkuSeckillInfo(@PathVariable("skuId") Long skuId) {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SeckillSkuRedisTO redisTOS = seckillService.getSkuSeckillInfo(skuId);
        return R.ok().setData(redisTOS);
    }

    @GetMapping("/kill")
    public String seckill(@RequestParam("killId") String killId,
                          @RequestParam("key") String key,
                          @RequestParam("num") Integer num, Model model) {
        // 判断是否登录
        String orderSn = seckillService.seckill(killId, key, num);
        model.addAttribute("orderSn", orderSn);
        return "success";
    }
}
